<?php

namespace App\Repositories\Sku;

use Illuminate\Container\Container as App;
use Prettus\Repository\Eloquent\BaseRepository as Repository;
use App\Repositories\Sku\AttrRepository as Attr;
use App\Repositories\Sku\SpecRepository as Spec;
use App\Repositories\Sku\ItemRepository as Item;

class ProductRepository extends Repository
{
    public function model()
    {
        return 'App\Models\Sku\Product';
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($request)
    {
        $shop_id = $request->shop;

        if (!$shop_id) {
            $result = $this->model->with('shop','items')
                ->orderBy('id', 'desc')
                ->paginate(30);
        } else {
            $result = $this->model
                ->where('name', 'like', "%$query%")
                ->paginate(30);
        }
        return $result;
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store($request)
    {
        $fillable = $this->model->getFillable();
        
        \DB::beginTransaction();
        try {
            $product = $this->create($request->only($fillable));

            if(!!$product){
                
                $product->setImages($request);

                $product->setItems($request);
            }

            \DB::commit();
            return responseSuccess('增加商品成功');

        } catch (\Exception $e) {
            \DB::rollback();
            return responseFail(500, '增加商品失败');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $product = $this->find($id);

        if (!$product) {
            return responseFail(404);
        }

        $product->load('items','shop','category.parent');

        $product->skuAttrs = $this->getSkuAttrs($product);        
        $product->checkAttrs = $this->getCheckAttrs($product);
        $product->cover_pic= $this->getBase64Image($product->cover_pic);
        $product->share_pic= $this->getBase64Image($product->share_pic);

        return $product;
    }


    public function renew($request, $id)
    {
        $fillable = $this->model->getFillable();
        
        \DB::beginTransaction();
        try {
            $product = $this->update($request->only($fillable), $id);

            if(!!$product){
                
                $product->updateImages($request);

                $product->updateItems($request);
            }

            \DB::commit();
            return responseSuccess('修改成功');

        } catch (\Exception $e) {
            \DB::rollback();
            return responseFail(500, '修改失败');
        }
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }


    /**
     * Get the SKU display property
     * @param  [type] $product [description]
     * @return [type]          [description]
     */
    protected function getSkuAttrs($product)
    {
        $result = array();

        if($product->sku_flag == STATUS_ZERO)
            return json_encode($result);

        foreach($product->attrs as $i=>$attr){
            $result[$i] = array('attr_name'=>$attr->name);

            foreach($attr->specs as $j=>$spec){
                $result[$i]['sku_list'][$j] = array('spec_id'=>$spec->id,'spec_name'=>$spec->name);
            }
        }
        //dd($result);
        return json_encode($result);
    }


    /**
     * Get the SKU items from database
     * @param  [type] $product [description]
     * @return [type]          [description]
     */
    protected function getCheckAttrs($product)
    {
        $result = array();
        
        if($product->sku_flag == STATUS_ZERO)
            return json_encode($result);

        if( \Cache::has(CACHE_SKU_SPEC.':'.$product->id)){
            $cache = \Cache::get(CACHE_SKU_SPEC.':'.$product->id);
        }            
        else{
            $cache = $product->specs;
        }

        foreach($product->items as $i=>$item){
            $itemList[$i][SKU_LIST] = json_decode($item->sku,true);
            $itemList[$i]['id'] = $item['id'];
            $itemList[$i]['price'] = $item['price'];
            $itemList[$i]['origin'] = $item['origin'];
            $itemList[$i]['settlement'] = $item['settlement'];
            $itemList[$i]['stock'] = $item['stock'];
        }

        foreach($itemList as $i=>$skuList){
            foreach($skuList[SKU_LIST] as $j=>$sku){
                $attrs = explode(':',$sku);
                $query[] = $attrs[1];
                $attr_name = '';//$this->attr->find($attrs[0])->name;
                $spec_name = $cache->find($attrs[1])->name;
                $skuList[SKU_LIST][$j] = array('attr_id'=>$attrs[0],'attr_name'=>$attr_name,'spec_id'=>$attrs[1],'spec_name'=>$spec_name);
            }
            $itemList[$i] = $skuList;
        }

        return json_encode($itemList);
    }

    protected function getBase64Image($file)
    {
        $result = '';

        $img = public_path().$file;
        $info = getimagesize($img);
        $data = fread(fopen($img, 'r'), filesize($img));
        $result = 'data:' . $info['mime'] . ';base64,' . chunk_split(base64_encode($data));
        
        return $result;
    }


}
